package com.qxsx.midi.activity.exam;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.qxsx.midi.R;
import com.qxsx.midi.activity.base.BaseActivity;
import com.qxsx.midi.activity.home.MusicDetailsActivity;
import com.qxsx.midi.adapter.AddressAdapter;
import com.qxsx.midi.config.AppContext;
import com.qxsx.midi.model.Address;
import com.qxsx.midi.model.Apply;
import com.qxsx.midi.model.ClassVideo;
import com.qxsx.midi.utils.CustomProgress;
import com.qxsx.midi.utils.MyNet;
import com.qxsx.midi.utils.SPUtils;
import com.qxsx.midi.utils.callBackJsonArray;
import com.qxsx.midi.view.XListView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by Joney on 2015/9/10.
 */
public class ChooseAddressActivity extends Activity implements OnClickListener, XListView.IXListViewListener {
    private CustomProgress customProgress;

    private ArrayList<Address> lists;
    private List<Address> allLists;
    private int page = 1;//初始化页号为1

    private AddressAdapter adapter;

    private XListView lv_address;
    private Handler mHandler;  //执行下拉、上拉线程
    private TextView tv_name;

    public static final int REQUSET = 1;
    private EditText et_name;

    private LinearLayout ll_back,ll_address;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_choose_address);
        findById();


        lv_address.setPullLoadEnable(true);
        lv_address.setPullRefreshEnable(true);
        mHandler = new Handler();
        lv_address.setXListViewListener(this);


    }


    private void inItData() {
        allLists = new ArrayList<>();
        lists = new ArrayList<>();
//        for (int i = 0; i < 10; i++) {
//            Address address = new Address();
//            lists.add(address);
//        }
        adapter = new AddressAdapter(ChooseAddressActivity.this, lists);
        lv_address.setAdapter(adapter);

        chooseaddress(1);
    }


    @Override
    protected void onResume() {
        super.onResume();
        inItData();
        final String apply_city_name = (String) SPUtils.get(AppContext.getContext(), "apply_city_name", "");
        tv_name.setText(apply_city_name);
        lv_address.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                String address = allLists.get(position - 1).getAd_address();
                SPUtils.put(AppContext.getContext(), "choos_address", apply_city_name + address);
                SPUtils.put(AppContext.getContext(), "exam_site_id", allLists.get(position - 1).getAd_id());
//                //Intent it = new Intent(ChooseAddressActivity.this, ApplyActivity.class);
//                Intent it = new Intent(ChooseAddressActivity.this, ApplyActivity.class);
//
//                // it.putExtra("id", allLists.get(position - 1).getAd_id());//传递商家ID
//                startActivity(it);
                finish();
            }
        });
    }


    private void chooseaddress(int page) {
        customProgress = CustomProgress.show(ChooseAddressActivity.this, "正在加载中....", true, null);

        JSONObject object = new JSONObject();
        JSONArray array = new JSONArray();
        String apply_city_id = (String) SPUtils.get(AppContext.getContext(), "apply_city_id", "120100");

        try {
            object.put("club_city", apply_city_id );
            object.put("nowpage", page + "");
            object.put("pagesize", "10");
            object.put("site_name", et_name.getText().toString().trim());
            array.put(object);


        } catch (JSONException e) {
            e.printStackTrace();
        }

        MyNet.doPostJsonArray("503", array, new callBackJsonArray() {
            @Override
            public void run(Object code, Object message, JSONArray array) {
                if (array == null) {
                    return;
                }
                try {
                    lists = new ArrayList<Address>();
                    for (int i = 0; i < array.length(); i++) {
                        JSONObject object1 = array.getJSONObject(i);
                        Address address = new Address();
                        address.setAd_id(object1.getString("id"));
                        address.setAd_name(object1.getString("exam_site_name"));
                        address.setAd_address(object1.getString("address"));
                        //Log.w("lesson_icon", object1.getString("lesson_icon"));
                        lists.add(address);
                        allLists.add(address);
                    }
                    adapter.removeAll();
                    adapter.addData(lists);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                customProgress.dismiss();
            }
        });


    }
//搜索的时候用到
    private void chooseaddresss(int page) {
        customProgress = CustomProgress.show(ChooseAddressActivity.this, "正在加载中....", true, null);

        JSONObject object = new JSONObject();
        JSONArray array = new JSONArray();
        String apply_city_id = (String) SPUtils.get(AppContext.getContext(), "apply_city_id", "120100");

        try {
            //object.put("club_city", apply_city_id );
            object.put("nowpage", page + "");
            object.put("pagesize", "10");
            object.put("site_name", et_name.getText().toString().trim());
            array.put(object);


        } catch (JSONException e) {
            e.printStackTrace();
        }

        MyNet.doPostJsonArray("503", array, new callBackJsonArray() {
            @Override
            public void run(Object code, Object message, JSONArray array) {
                if (array == null) {
                    return;
                }
                try {
                    lists = new ArrayList<Address>();
                    for (int i = 0; i < array.length(); i++) {
                        JSONObject object1 = array.getJSONObject(i);
                        Address address = new Address();
                        address.setAd_id(object1.getString("id"));
                        address.setAd_name(object1.getString("exam_site_name"));
                        address.setAd_address(object1.getString("address"));
                        //Log.w("lesson_icon", object1.getString("lesson_icon"));
                        lists.add(address);
                        allLists.add(address);
                    }
                    adapter.removeAll();
                    adapter.addData(lists);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                customProgress.dismiss();
            }
        });


    }

    /**
     * 上啦加载
     */
    private void LoadMore() {
        page++;
        JSONObject object = new JSONObject();
        JSONArray array = new JSONArray();
        String apply_city_id = (String) SPUtils.get(AppContext.getContext(), "apply_city_id", "120100");

        try {
            object.put("club_city", apply_city_id);
            object.put("nowpage", page + "");
            object.put("pagesize", "10");
            object.put("site_name", et_name.getText().toString().trim());

            array.put(object);


        } catch (JSONException e) {
            e.printStackTrace();
        }

        MyNet.doPostJsonArray("503", array, new callBackJsonArray() {
            @Override
            public void run(Object code, Object message, JSONArray array) {
                if (array == null) {
                    return;
                }
                try {
                    lv_address.stopLoadMore();
                    lists = new ArrayList<Address>();
                    for (int i = 0; i < array.length(); i++) {
                        JSONObject object1 = array.getJSONObject(i);
                        Address address = new Address();
                        address.setAd_id(object1.getString("id"));
                        address.setAd_name(object1.getString("exam_site_name"));
                        address.setAd_address(object1.getString("address"));
                        //Log.w("lesson_icon", object1.getString("lesson_icon"));
                        lists.add(address);
                        allLists.add(address);
                    }
                    adapter.addData(lists);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });


    }

    /**
     * 下拉刷新
     */
    private void LoadRefresh() {
        page = 1;
        allLists.clear();
        JSONObject object = new JSONObject();
        JSONArray array = new JSONArray();
        String apply_city_id = (String) SPUtils.get(AppContext.getContext(), "apply_city_id", "120100");
        try {
            object.put("club_city", apply_city_id);
            object.put("nowpage", 1 + "");
            object.put("pagesize", "10");
            object.put("site_name", et_name.getText().toString().trim());

            array.put(object);


        } catch (JSONException e) {
            e.printStackTrace();
        }

        MyNet.doPostJsonArray("503", array, new callBackJsonArray() {
            @Override
            public void run(Object code, Object message, JSONArray array) {
                if (array == null) {
                    return;
                }
                try {
                    lv_address.stopRefresh();
                    SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");//设置日期格式
                    lv_address.setRefreshTime(df.format(new Date()));
                    lists = new ArrayList<Address>();
                    for (int i = 0; i < array.length(); i++) {
                        JSONObject object1 = array.getJSONObject(i);
                        Address address = new Address();
                        address.setAd_id(object1.getString("id"));
                        address.setAd_name(object1.getString("exam_site_name"));
                        address.setAd_address(object1.getString("address"));
                        //Log.w("lesson_icon", object1.getString("lesson_icon"));
                        lists.add(address);
                        allLists.add(address);
                    }
                    adapter.removeAll();
                    adapter.addData(lists);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });
    }

    /**
     * 下拉刷新
     */
    @Override
    public void onRefresh() {
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                LoadRefresh();
            }
        }, 2000);

    }

    /**
     * 上拉加载更多
     */
    @Override
    public void onLoadMore() {
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                LoadMore();
            }
        }, 2000);


    }


    private void findById() {
        ll_back = (LinearLayout) findViewById(R.id.ll_back);
        ll_back.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        ll_address = (LinearLayout) findViewById(R.id.ll_address);
        ll_address.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(ChooseAddressActivity.this, CityListActivity.class);
                //startActivity(new Intent(ChooseAddressActivity.this, CityListActivity.class));
                startActivityForResult(intent, REQUSET);
            }
        });
        lv_address = (XListView) findViewById(R.id.lv_address);
        tv_name = (TextView) findViewById(R.id.tv_name);
        et_name = (EditText) findViewById(R.id.et_name);
        et_name.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
        et_name.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH || (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                    //do something;
//                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
//                    imm.hideSoftInputFromWindow(et_password.getWindowToken(), 0);
                    chooseaddresss(1);
                    return true;
                }
                return false;
            }
        });

    }



//    @Override
//    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
//        if (requestCode == ChooseAddressActivity.REQUSET && resultCode == RESULT_OK) {
//            data.getStringExtra(CityListActivity.CITY_ID);
//            SPUtils.put(AppContext.getContext(), "apply_city_id", data.getStringExtra(CityListActivity.CITY_ID));
//            Log.w("data", data.getStringExtra(CityListActivity.CITY_ID) + "");
//        }
//
//    }




    @Override
    public void onClick(View v) {

    }
}
